package com.coovane.bytetrix.common.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 对象转换帮助类
 * 由于本项目基于JDK17，所以有些方法已经被标记@Deprecated
 * 比如class.newInstance()
 * </p>
 *
 * @author: Hsu
 * @date: 2022/11/26 21:09
 * @copyright: companyName
 * @see
 * @since 1.8
 */
public class ConvertUtils {

    @SneakyThrows
    public static <S, T> T convert(S source, Class<T> clazz) {
        if (Objects.isNull(source)) {
            return null;
        }
        T target = clazz.getDeclaredConstructor().newInstance();
        Copier.copy(source, target);
        return target;
    }

    @SneakyThrows
    public static <S, T> List<T> convertForList(Collection<S> source, Class<T> clazz) {
        List<T> list = Lists.newArrayList();
        if (CollectionUtils.isEmpty(source)) {
            return list;
        }

        for (S bean : source) {
            T target = clazz.getDeclaredConstructor().newInstance();
            Copier.copy(bean, target);
            list.add(target);
        }
        return list;
    }

    @SneakyThrows
    public static <S, T> Page<T> convertForPage(Page<S> sourcePage, Class<T> clazz) {
        Page<T> targetPage = new Page<>();
        targetPage.setCurrent(sourcePage.getCurrent());
        targetPage.setSize(sourcePage.getSize());
        targetPage.setPages(sourcePage.getPages());
        targetPage.setTotal(sourcePage.getTotal());
        ArrayList<T> targetList = Lists.newArrayListWithCapacity((int) sourcePage.getSize());
        List<S> records = sourcePage.getRecords();
        records.forEach(e -> targetList.add(convert(e, clazz)));
        targetPage.setRecords(targetList);
        return targetPage;
    }

}
